package qingyu.ai.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iflytek.cloud.SpeechError;
import com.vondear.rxtools.view.RxToast;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import qingyu.ai.R;
import qingyu.ai.base.BaseActivity;
import qingyu.ai.common.Constants;
import qingyu.ai.common.net.APIFactory;
import qingyu.ai.common.net.NetRequestAdapter;
import qingyu.ai.common.net.NetworkRequestCalback;
import qingyu.ai.common.speech.recognizer.RecognizerAdapter;
import qingyu.ai.common.speech.recognizer.RecognizerCallBack;
import qingyu.ai.common.speech.recognizer.SpeechRecognizerWrapper;
import qingyu.ai.common.speech.synthesizer.SpeechSynthesizerWrapper;
import qingyu.ai.common.speech.synthesizer.SynthesizerAdapter;
import qingyu.ai.common.speech.synthesizer.SynthesizerCallback;
import qingyu.ai.common.util.ActManager;
import qingyu.ai.common.util.FuncUtil;
import qingyu.ai.common.util.SPUtil;
import qingyu.ai.domain.TuLin;
import qingyu.ai.domain.TuLinResult;
import qingyu.ai.ui.about.AboutActivity;
import qingyu.ai.ui.clock.EventAndRemindActivity;
import qingyu.ai.ui.feedback.FeedBackActivity;
import qingyu.ai.ui.guide.GuideActivity;
import qingyu.ai.ui.personal.PersonalActivity;
import qingyu.ai.ui.safe.login.LoginActivity;
import qingyu.ai.ui.settings.SettingsActivity;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, RecognizerCallBack, SynthesizerCallback, NetworkRequestCalback<TuLinResult> {

    private long doubleHitExit;//双击推出app
    private float rawX1;
    private float rawX2;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.nav_view)
    NavigationView navigationView;

    @BindView(R.id.speak_volume)
    CheckBox speak_volume;
    SimpleDraweeView user_avatar;
    TextView user_account;

    @BindView(R.id.iv_recognizer)
    ImageView iv_recognizer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initConfig();
        initToolBar(toolbar, R.string.app_name, R.mipmap.navbar_icon_usher);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        initNavgationView();
    }

    private void initNavgationView() {
        navigationView.setNavigationItemSelectedListener(this);
        user_avatar = navigationView.getHeaderView(0).findViewById(R.id.user_avatar);
        user_account = navigationView.getHeaderView(0).findViewById(R.id.user_account);

        user_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String access_token = SPUtil.getString(Constants.userinfo.access_token, null);
                if (!TextUtils.isEmpty(access_token)) {
                    MainActivity.this.startActivity(new Intent(MainActivity.this, PersonalActivity.class));
                } else {
                    MainActivity.this.startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
                drawer.closeDrawer(GravityCompat.START);

            }
        });
    }

    private void initConfig() {
        if (SPUtil.getBoolean(Constants.guide.IS_FIRST_USE, true)) {
            SPUtil.putBoolean(Constants.guide.IS_FIRST_USE, false);
            SPUtil.putString(Constants.settings.VOICER, "vinn");//默认音色为vinn
            SPUtil.putBoolean(Constants.settings.IS_SYNTHES_PLAY, true);//默认语音播报
            SPUtil.putBoolean(Constants.settings.WAKE_SWITCH, true);//默认唤醒为开
            SPUtil.putString(Constants.settings.CHECKED_WAKEWORD1, getString(R.string.first_wake_word));//默认唤醒词为你好息息
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //语音是否播报
        isSynthesSpeak(SPUtil.getBoolean(Constants.settings.IS_SYNTHES_PLAY, true));

        //更新侧栏头像和账号
        String account = SPUtil.getString(Constants.userinfo.nickname, null);
        String iconUrl = SPUtil.getString(Constants.userinfo.iconUrl, null);
        //头像
        FuncUtil.defaultOrUserIcon(user_avatar, iconUrl, R.mipmap.headportrait);
        //昵称
        FuncUtil.defaultOrUserNickName(user_account, account, R.string.login);
    }

    private void isSynthesSpeak(boolean isSpeak) {
        int resid = !isSpeak ? R.mipmap.navbar_icon_volume_off : R.mipmap.navbar_icon_volume_on_default;
        speak_volume.setBackgroundResource(resid);
    }

    /**
     * 是否播报
     *
     * @param ischecked 如果为true，则进行播报
     */
    @OnCheckedChanged(R.id.speak_volume)
    public void synthesToggle(boolean ischecked) {
        if (!ischecked)
            SpeechSynthesizerWrapper.createSynthesizerCommond(this).getSynthesizer().pauseSpeaking();
        else
            SpeechSynthesizerWrapper.createSynthesizerCommond(this).getSynthesizer().resumeSpeaking();

        SPUtil.putBoolean(Constants.settings.IS_SYNTHES_PLAY, ischecked);
        isSynthesSpeak(ischecked);
    }

    @OnClick(R.id.iv_feedback)
    public void toFeedBack() {
        startActivity(new Intent(this, FeedBackActivity.class));
    }

    @OnClick(R.id.to_event_page)
    public void toEventPage() {
        startActivity(new Intent(this, EventAndRemindActivity.class));
    }


    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (System.currentTimeMillis() - doubleHitExit < 2000) {
                ActManager.getAppManager().AppExit(this);
                super.onBackPressed();
            } else {
                doubleHitExit = System.currentTimeMillis();
                RxToast.normal("再按一次退出程序", Toast.LENGTH_SHORT);
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Intent intent = null;
        switch (item.getItemId()) {
            case R.id.leading://引导帮助
                intent = new Intent(this, GuideActivity.class);
                break;
            case R.id.setting://设置
                intent = new Intent(this, SettingsActivity.class);
                break;
            case R.id.feed_back://反馈
                intent = new Intent(this, FeedBackActivity.class);
                break;
            case R.id.about://关于我们
                intent = new Intent(this, AboutActivity.class);
                break;
        }
        if (intent != null)
            startActivity(intent);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 左滑
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            rawX1 = event.getRawX();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            rawX2 = event.getRawX();
            if (rawX1 - rawX2 > 50 && !drawer.isDrawerOpen(GravityCompat.START)) {
                startActivity(new Intent(this, EventAndRemindActivity.class));
            }
        }
        return super.dispatchTouchEvent(event);
    }

    @OnClick(R.id.iv_recognizer)
    public void recognizer() {
        Log.e("wfy", "hahaha");
        SpeechRecognizerWrapper.createRecognizerCommond(this)
                .initRecognizerParam()
                .startRecognnizer(new RecognizerAdapter(this));
    }

    @Override
    public void onRecognizerResult(String result) {
        Log.e("wfy", result + "----");
        new APIFactory(this, "http://www.tuling123.com/openapi/api/")
                .tulin(new TuLin("08a30ef546214cf5bc720f34e05a3a58", result, "12334234235"), new NetRequestAdapter<TuLinResult>(this));

    }

    @Override
    public void onSuccess(TuLinResult data) {
        if (SPUtil.getBoolean(Constants.settings.IS_SYNTHES_PLAY, true)) {
            SpeechSynthesizerWrapper.createSynthesizerCommond(this)
                    .initReadParams(SPUtil.getString(Constants.settings.VOICER, "vinn"), "", "", "100")
                    .startSpeaking(data.getText(), new SynthesizerAdapter(this));
        }
    }

    @Override
    public void onError(int errCode, String errMsg) {
        Log.e("wfy", errCode + "----" + errMsg);

    }

    @Override
    public void onNetStart() {

    }

    @Override
    public void onNetFinish() {

    }

    @Override
    public void onCompleted(SpeechError speechError) {

    }
}
